package com.q.tqb.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.q.tqb.activity.login.LoginActivity;
import com.q.tqb.service.AppUpdateService;
import com.q.tqb.R;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;


import com.q.tqb.base.BaseApplication;
import com.q.tqb.fragment.GrabFragment;
import com.q.tqb.fragment.HomeFragment;
import com.q.tqb.fragment.MineFragment;
import com.q.tqb.fragment.SocietyFragment;
import com.q.tqb.model.AppUpdateInfo;
import com.q.tqb.model.UserInfo;
import com.q.tqb.util.DeviceUtil;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.VersionUtil;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.view.popwindow.SendPopWindow;
import com.q.tqb.view.dialog.LoginDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @author Administrator
 * 主界面
 */
public class MainActivity extends BaseActivity {


    @BindView(R.id.fl_content)
    FrameLayout mFlContent;
    @BindView(R.id.iv_home)
    ImageView mIvHome;
    @BindView(R.id.tv_home)
    TextView mTvHome;
    @BindView(R.id.rl_home)
    RelativeLayout mRlHome;
    @BindView(R.id.iv_grab)
    ImageView mIvGrab;
    @BindView(R.id.tv_grab)
    TextView mTvGrab;
    @BindView(R.id.rl_grab)
    RelativeLayout mRlGrab;
    @BindView(R.id.iv_society)
    ImageView mIvSociety;
    @BindView(R.id.tv_society)
    TextView mTvSociety;
    @BindView(R.id.rl_society)
    RelativeLayout mRlSociety;
    @BindView(R.id.iv_mine)
    ImageView mIvMine;
    @BindView(R.id.tv_mine)
    TextView mTvMine;
    @BindView(R.id.rl_mine)
    RelativeLayout mRlMine;
    @BindView(R.id.iv_send)
    ImageView mIvSend;
    @BindView(R.id.tv_city)
    TextView mTvCity;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;

    private GrabFragment mGrabFragment;
    private HomeFragment mHomeFragment;
    private MineFragment mMineFragment;
    private SocietyFragment mSocietyFragment;
    private FragmentManager fragmentManager;

    //    private LoginDialog loginDialog;
    private int index;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private MyBroadcastReceiver mBroadcastReceiver;
    private boolean isLogin;
    private ProgressDialog mDialog;
    private long mExitTime;
    private SendPopWindow mMoreWindow;
    public boolean isTweeterOpen;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("SAVED_INDEX", index);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void init(Bundle savedInstanceState) {

        setTitle(R.string.app_name);

        //初始化登录
        initLogin();
        //初始化fragment页面布局
        initFragment(savedInstanceState);
        //初始化定位
        initLocation();
        //初始化定位
        initReceiver();
        updateApp();

        //connect("test");

    }

    /**
     * 登录情况
     */
    private void initLogin() {

//        loginDialog = new LoginDialog(this);
        isLogin = (boolean) SPUtil.get(this, "isLogin", false);
        if (!isLogin) {
//            loginDialog.show();
            startActivityForResult(new Intent(this, LoginActivity.class), 51);
        } else {
            int uid = (int) SPUtil.get(this, "uid", 0);
            if (uid != 0) {
                JPushInterface.setAliasAndTags(getApplicationContext(), uid + "", null, new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        LogUtil.i("极光推送设置别名成功");
                    }
                });
            }
            getUserInfo(uid);
        }

    }

    /**
     * 获得个人信息
     */
    private void getUserInfo(int uid) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("uid", uid + "");
        hashMap.put("token", StringUtil.getToken(uid));
        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_USER_INFO, hashMap, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                UserInfo personData = gson.fromJson(result, UserInfo.class);
                //手机
                SPUtil.put(MainActivity.this, "mobile", personData.getMobile());
                //支付密码
//                SPUtil.put(MainActivity.this, "payPassword", personData.getPay_password());
                //用户uid 唯一标识码
                SPUtil.put(MainActivity.this, "uid", personData.getUid());
                //获得红包金额
                SPUtil.put(MainActivity.this, "getMoney", personData.getGet_money());
                //发红包金额
                SPUtil.put(MainActivity.this, "postMoney", personData.getPost_money());
                //账户余额
//                SPUtil.put(MainActivity.this, "withdraw", personData.getWithdraw_cash());
                //是否推客
//                SPUtil.put(MainActivity.this, "isUserAgent", personData.getIs_users_agent());
                //是否商户
//                SPUtil.put(MainActivity.this, "isMerchant", personData.getIs_merchant());
                //是否对外显示
//                SPUtil.put(MainActivity.this, "isShow", personData.getIs_show_privacy());
                //个人签名
//                SPUtil.put(MainActivity.this, "isSignature", personData.getSignature());

                SPUtil.put(MainActivity.this, "level", personData.getLevel());
                SPUtil.put(MainActivity.this, "level_name", personData.getLevel_name());
                SPUtil.put(MainActivity.this, "is_max_level", personData.getIs_max_level());

                SPUtil.put(MainActivity.this, "is_community", personData.getIs_community());
                SPUtil.put(MainActivity.this, "agent_type", personData.getAgent_type());
                SPUtil.put(MainActivity.this, "agent_name", personData.getAgent_name());
                SPUtil.put(MainActivity.this, "agent_name", personData.getAgent_name());
                //头部图片
                SPUtil.put(MainActivity.this, "header", personData.getHeader());
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                //mProgressDialog.dismiss();
                LogUtil.i(errorMsg);
                // showToast(getString(R.string.main_login_fail));

            }
        });
    }

    /**
     * 初始化fragment
     */
    private void initFragment(Bundle savedInstanceState) {

        //判断保存定位地点
        String city = SPUtil.getString(this, "city");
        if (!TextUtils.isEmpty(city)) {
            mTvCity.setText(city);
        }

        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            index = savedInstanceState.getInt("SAVED_INDEX", index);
            mHomeFragment = (HomeFragment) fragmentManager.findFragmentByTag("HOME");
            mGrabFragment = (GrabFragment) fragmentManager.findFragmentByTag("GRAB");
            mSocietyFragment = (SocietyFragment) fragmentManager.findFragmentByTag("SOCIETY");
            mMineFragment = (MineFragment) fragmentManager.findFragmentByTag("MINE");
        }


        setTabSelection(0);
    }

    /**
     * 微信登录回调（拿code码）
     */
    private void initReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.WX_LOGIN);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }


    /**
     * 百度地图定位
     */
    private void initLocation() {
        mLocationClient = new LocationClient(this.getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(false);
        option.setAddrType("all");
        option.setIgnoreKillProcess(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    /**
     * 双击退出APP
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                showToast(getString(R.string.main_exit));
                mExitTime = System.currentTimeMillis();
            } else {
                BaseApplication.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick({R.id.rl_home, R.id.rl_grab, R.id.rl_society, R.id.rl_mine, R.id.iv_send, R.id.iv_right, R.id.iv_location, R.id.tv_city})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_home:
                index = 0;
                setTabSelection(0);
                break;
            case R.id.rl_grab:
                index = 1;
                setTabSelection(1);
                break;
            case R.id.rl_society:
                index = 2;
                setTabSelection(2);
                break;
            case R.id.rl_mine:
                index = 3;
                setTabSelection(3);
                break;
            case R.id.iv_send:
                showMoreWindow(view);
                break;
            case R.id.iv_right:
                break;
            case R.id.iv_location:
            case R.id.tv_city:
                mProgressDialog.show();
                initLocation();
                //       RongIM.getInstance().startConversation(MainActivity.this, Conversation.ConversationType.PRIVATE, "42", "龚帅哥");
                break;
            default:
                break;
        }
    }

    /**
     * 选择fragment页面
     */
    private void setTabSelection(int index) {
        clearSelection();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                setTitle(getString(R.string.app_name));
                mTvCity.setVisibility(View.VISIBLE);
                mIvLocation.setVisibility(View.VISIBLE);
                mIvHome.setSelected(true);
                mTvHome.setSelected(true);

                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.newInstance();
                    transaction.add(R.id.fl_content, mHomeFragment, "HOME");

                    mHomeFragment.setOnTweeterClick(new HomeFragment.OnTweeterClick() {
                        @Override
                        public void onTweeter() {
                            setTabSelection(1);
                            isTweeterOpen = true;
                        }
                    });
                } else {
                    transaction.show(mHomeFragment);
                    mHomeFragment.setOnTweeterClick(new HomeFragment.OnTweeterClick() {
                        @Override
                        public void onTweeter() {
                            setTabSelection(1);
                            isTweeterOpen = true;
                        }
                    });
                }
                break;
            case 1:
                setTitle(getString(R.string.main_grab_red));
                mIvGrab.setSelected(true);
                mTvGrab.setSelected(true);
                if (mGrabFragment == null) {
                    mGrabFragment = GrabFragment.newInstance();
                    transaction.add(R.id.fl_content, mGrabFragment, "GRAB");
                } else {
                    transaction.show(mGrabFragment);
                }
                if (isTweeterOpen) {
                    isTweeterOpen = false;
                    mGrabFragment.setCurrent(0);
                }
                break;
            case 2:
                setTitle(getString(R.string.main_rank));
                mIvSociety.setSelected(true);
                mTvSociety.setSelected(true);

                if (mSocietyFragment == null) {
                    mSocietyFragment = SocietyFragment.newInstance();
                    transaction.add(R.id.fl_content, mSocietyFragment, "SOCIETY");
                } else {
                    transaction.show(mSocietyFragment);
                }
                break;
            case 3:
                setTitle(getString(R.string.main_mine));
                mIvMine.setSelected(true);
                mTvMine.setSelected(true);
                if (mMineFragment == null) {
                    mMineFragment = MineFragment.newInstance();
                    transaction.add(R.id.fl_content, mMineFragment, "MINE");
                } else {
                    transaction.show(mMineFragment);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }


    /**
     * 清理fragment状态
     */
    private void clearSelection() {
        mTvCity.setVisibility(View.GONE);
        mIvLocation.setVisibility(View.GONE);
        mIvRight.setVisibility(View.GONE);
        mIvHome.setSelected(false);
        mTvHome.setSelected(false);
        mIvGrab.setSelected(false);
        mTvGrab.setSelected(false);
        mIvSociety.setSelected(false);
        mTvSociety.setSelected(false);
        mIvMine.setSelected(false);
        mTvMine.setSelected(false);
    }


    /**
     * 弹出发送红包弹窗
     *
     * @param view 定位view
     */
    private void showMoreWindow(View view) {
        if (null == mMoreWindow) {
            mMoreWindow = new SendPopWindow(this);
            mMoreWindow.init();
        }
        mMoreWindow.showMoreWindow(view);
    }

    /**
     * 隐藏fragment
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
        if (mGrabFragment != null) {
            transaction.hide(mGrabFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }
        if (mSocietyFragment != null) {
            transaction.hide(mSocietyFragment);
        }
    }


    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            wxLogin(code);
        }
    }


    /**
     * 百度定位回调
     */
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            String city = location.getCity();
            String province = location.getProvince();
            String district = location.getDistrict();
            String address = province + "-" + city + "-" + district;
            SPUtil.put(MainActivity.this, "address", address);
            SPUtil.put(MainActivity.this, "city", city);
            mTvCity.setText(city);
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("address", address);
            LogUtil.i(hashMap.toString());
            OkHttpUtil.getInstance().post(MainActivity.this, AppConst.URL_GET_ADDRESS_CODE, hashMap, new IResponse() {
                @Override
                public void onSuccess(JsonElement element) {
                    mProgressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(element.toString());
                        String addressCode = jsonObject.getString("addressCode");
                        SPUtil.put(MainActivity.this, "addressCode", addressCode);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, String errorMsg) {
                    mProgressDialog.dismiss();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 51 && resultCode != RESULT_OK) {
//            loginDialog.dismiss();
            this.finish();
        }
    }


    /**
     * 检测APP版本
     */
    private void updateApp() {
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_APP_VERSION, null, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                Gson gson = new Gson();
                AppUpdateInfo appUpdateInfo = gson.fromJson(element, AppUpdateInfo.class);
                int nowVersion = VersionUtil.getAppVersionName(MainActivity.this);
                if (appUpdateInfo.getVersion() > nowVersion) {
                    showUpdateDialog(appUpdateInfo.getVsersion_msg());
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                mProgressDialog.dismiss();
            }
        });
    }


    /**
     * 显示APP升级对话框
     *
     * @param message 升级信息
     */
    private void showUpdateDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle("版本更新")
                .setMessage(message)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mDialog = new ProgressDialog(MainActivity.this);
                        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        mDialog.setCancelable(true);
                        mDialog.setCanceledOnTouchOutside(false);
                        mDialog.setIcon(R.drawable.ic_logo);
                        mDialog.setTitle("版本升级");
                        mDialog.setMax(100);
                        mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                });
                        mDialog.setMessage("正在升级...");
                        mDialog.show();
                        AppUpdateService.startUpdate(MainActivity.this, AppConst.UPDATE_APP, getExternalCacheDir() + "tqb.apk", new AppUpdateService.OnProgressListener() {
                            @Override
                            public void onProgress(int progress) {
                                //更新对话框进度条
                                mDialog.setProgress(progress);
                            }

                            @Override
                            public void onSuccess(boolean isSuccess) {
                                mDialog.dismiss();
                                //失败提示
                                if (!isSuccess) {
                                    showToast("更新不成功");
                                }
                            }
                        });

                    }
                })
                .setNegativeButton(R.string.string_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }


    /**
     * 微信登录
     *
     * @param code 微信返回code码
     */
    private void wxLogin(final String code) {
        mProgressDialog.show();
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("code", code);
        OkHttpUtil.getInstance().post(this, AppConst.URL_WX_LOGIN, hashMap, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                UserInfo personData = gson.fromJson(result, UserInfo.class);
                showToast(getString(R.string.main_login_success));
                //昵称
                SPUtil.put(MainActivity.this, "nickname", personData.getNickname());
                //头部图片
                SPUtil.put(MainActivity.this, "header", personData.getHeader());
                //性别
                SPUtil.put(MainActivity.this, "sex", personData.getSex());
                //手机
                SPUtil.put(MainActivity.this, "mobile", personData.getMobile());
                //支付密码
                SPUtil.put(MainActivity.this, "payPassword", personData.getPay_password());
                //微信openid
                SPUtil.put(MainActivity.this, "openid", personData.getOpenid());
                //用户uid 唯一标识码
                SPUtil.put(MainActivity.this, "uid", personData.getUid());
                //获得红包金额
                SPUtil.put(MainActivity.this, "getMoney", personData.getGet_money());
                //发红包金额
                SPUtil.put(MainActivity.this, "postMoney", personData.getPost_money());
                //账户余额
                SPUtil.put(MainActivity.this, "withdraw", personData.getWithdraw_cash());
                SPUtil.put(MainActivity.this, "unionid", personData.getUnionid());
                //是否推客
                SPUtil.put(MainActivity.this, "isUserAgent", personData.getIs_users_agent());
                //是否商户
                SPUtil.put(MainActivity.this, "isMerchant", personData.getIs_merchant());
                //是否登录
                SPUtil.put(MainActivity.this, "isLogin", true);
                //是否对外显示
                SPUtil.put(MainActivity.this, "isShow", personData.getIs_show_privacy());
                //个人签名
                SPUtil.put(MainActivity.this, "signature", personData.getSignature());

                JPushInterface.setAliasAndTags(getApplicationContext(), personData.getUid() + "", null, new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        LogUtil.i("极光推送设置别名成功");
                    }
                });
//                loginDialog.dismiss();
                isLogin = true;
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                mProgressDialog.dismiss();
                LogUtil.i(errorMsg);
                showToast(getString(R.string.main_login_fail));
            }
        });
    }


//    private void connect(String token) {
//        token = "j+met66V9105m1EEq9sPuHPnHjsgeT8TV6bEmU9a9mAmWqc+/dVr40lCcnAN2zmRnhNSOTtdJBB/qcYwTDzXXQ==";
//        if (getApplicationInfo().packageName.equals(DeviceUtil.getCurProcessName(getApplicationContext()))) {
//            RongIM.connect(token, new RongIMClient.ConnectCallback() {
//
//                /**
//                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
//                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
//                 */
//                @Override
//                public void onTokenIncorrect() {
//
//                }
//
//                /**
//                 * 连接融云成功
//                 * @param userid 当前 token 对应的用户 id
//                 */
//                @Override
//                public void onSuccess(String userid) {
////                    Log.d("LoginActivity", "--onSuccess" + userid);
////                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
////                    finish();
//                    LogUtil.i("userId," + userid);
//                }
//
//                /**
//                 * 连接融云失败
//                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
//                 */
//                @Override
//                public void onError(RongIMClient.ErrorCode errorCode) {
//
//                }
//            });
//        }
//    }

}
